﻿using LibVLCSharp.Shared;

namespace MusicDiary.Lib.Vlc;

public class VlcModel : IDisposable
{
    private readonly LibVLC _vlc;
    private readonly MediaPlayer Player;

    public void Dispose()
    {
        _vlc.Dispose();
        Player.Dispose();
    }

    #region event

    public delegate void PosFlushHandler(float a);

    public event PosFlushHandler? PosFlush;

    public delegate void DoneHandler();

    public event DoneHandler? Done;

    #endregion

    public VlcModel(bool debug = false, string a = "")
    {
        if (!string.IsNullOrEmpty(a))
            Core.Initialize();

        _vlc = new LibVLC(debug, a);
        Player = new MediaPlayer(_vlc);

        Player.PositionChanged += (sender, args) => PosFlush?.Invoke(args.Position);
        Player.EndReached += (sender, args) => Done?.Invoke();
    }


    #region Play

    public void Play()
    {
        ThreadPool.QueueUserWorkItem(_ => Player.Play());
    }

    public void Play(Uri url)
    {
        ThreadPool.QueueUserWorkItem(_ => Player.Play(new Media(_vlc, url)));
    }

    public void Play(Stream stream)
    {
        ThreadPool.QueueUserWorkItem(_ => Player.Play(new Media(_vlc, new StreamMediaInput(stream))));
    }

    #endregion

    #region Pos

    public void PosChange(float f) => Player.Position = f;

    public void FastForward(float f)
    {
        if (Player.Position + f < 1)
            Player.Position += f;
        else
            Player.Position = 1;
    }

    public void Return(float f)
    {
        if (Player.Position - f > 0)
            Player.Position -= f;
        else
            Player.Position = 0;
    }

    #endregion

    public void Pause()
    {
        ThreadPool.QueueUserWorkItem(_ => Player.Pause());
    }

    public void Stop()
    {
       Player.Stop();
    }
}